import random
from sre_parse import State
from django.http import JsonResponse
from website_server.models import ArticleTab, SystemInforms, TopicsTab
from website_server.utils import getID, getTime, http_post, model_to_list


# 系统消息类
class SystemInformsClass:
  def __init__(self,username,obj,cause=''):
    print(username)
    self.username = username
    self.obj = obj
    self.type = None
    self.text = None
    self.cause = cause

  # 创建系统消息
  def create(self,id):
    if id == 101: # 文章审核通过
      self.auditSuccess()
    elif id == 102: # 文章审核未通过
      self.auditFail()
    elif id == 103: # 举报成功
      self.reportSuccess()
    elif id == 104: # 举报失败
      self.reportFail()
    elif id == 105: # 删除评论
      self.removeComment()
    else:
      self.default()
    self .createSystemInforms()
  
  def createSystemInforms(self):
    informs = SystemInforms()
    informs.informsid = getID()
    informs.islook = 0
    informs.type = self.type
    informs.text = self.text + '感谢您的支持，祝您生活愉快！'
    informs.time = getTime()
    informs.username = self.username
    informs.save()
      
  # 审核成功
  def auditSuccess(self):
    obj = self.obj
    self.type = '文章审核通过'
    self.text = '您好，您在' + timer(obj.time) +'上传的标题为《' + obj.title + '》的文章审核' + obj.state + '，您可以继续发表更多文章了，'
  # 审核未通过
  def auditFail(self):
    obj = self.obj
    self.type = '文章审核未通过'
    self.text = '您好，您在' + timer(obj.time) +'上传的标题为《' + obj.title + '》的文章审核' + obj.state + '，原因是<' + self.cause + '>，您可以前往个人中心进行修改重新发布，'
  # 举报成功
  def reportSuccess(self):
    obj = self.obj
    self.type = '举报成功'
    self.text = '您好，您在' + timer(obj.time) + '举报的内容为《' + obj.cause + '》的' + self.cause + ',经查验确实存在违规已进行相关处理，'
  # 举报失败
  def reportFail(self):
    obj = self.obj
    self.type = '举报失败'
    self.text = '抱歉，您在' + timer(obj.time) + '举报的内容为《' + obj.cause + '》的' + self.cause + ',经查验并无违规内容已进行相关处理，'
  # 删除评论
  def removeComment(self):
    obj = self.obj
    self.type = '评论已删除'
    self.text = '抱歉，您的在' + timer(obj.time) + '发表的评论内容为《' + obj.content +'》因涉嫌违规已被删除，希望大家一起和平发言，营造绿色环境，' 

  def default(self):
    self.type = 'null'
    self.text = 'null'


# 时间转换
def timer(time):
  return time.strftime("%Y-%m-%d %H:%M:%S")

# 获取主页信息
@http_post
def getHomeInfo(request):
  video = TopicsTab.objects.filter(filetype='video').order_by('-time')[0:10]
  article = ArticleTab.objects.filter(state='已通过').order_by('?')[0:10]
  topics = TopicsTab.objects.all().order_by('?')[0:10]
  host = model_to_list(ArticleTab.objects.all().order_by('-visit')[0:5]) + model_to_list(TopicsTab.objects.all().order_by('-visit')[0:5])
  result = {
    'video': model_to_list(video),
    'article': model_to_list(article),
    'topics': model_to_list(topics),
    'host': host
  }
  return JsonResponse(result)
